//
//  CASecondViewController.m
//  qiche
//
//  Created by Seimei on 12-11-6.
//  Copyright (c) 2012年 iCar. All rights reserved.
//

#import "CASecondViewController.h"
#import "CAObject.h"
#import "CAAppDelegate.h"

@interface CASecondViewController ()
{
    CAVinObject*  _carVin;
    NSMutableArray* _carBrandList;
    NSMutableArray* _carSeriesList;
}
@end

@implementation CASecondViewController

#define kTitleLabelTag 33333
#define KET_CARDICT    @"carInfoPlist"
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = NSLocalizedString(@"车辆信息", @"车辆信息");
    }
    return self;
}
							
- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    _carVin = [CAAppDelegate globalAppdelegate].carVin;
    if (!_titleArray) {
        _titleArray = [[NSArray alloc] initWithObjects:@"VIN码:",@"是否试驾车",@"车牌号码:",@"车主姓名:",@"购买日期:",@"品牌:",@"生产厂家:",@"车型:",@"生产年份:",@"产地:",@"平均油耗:",@"保养间隔:",@"燃油种类:",@"车辆颜色:", nil];
    }

    if (!_dataDict) {
        NSUserDefaults* userDefaults=[NSUserDefaults standardUserDefaults];
        _dataDict = [userDefaults objectForKey:KET_CARDICT];
        if (!_dataDict) {
              _dataDict = [[NSMutableDictionary alloc] initWithContentsOfFile:[[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"carInfo.plist"]];
        }
    }
    [_dateView setHidden:YES];
    [self.view addSubview:_dateView];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    
    if (_dataDict) {
        [[NSUserDefaults standardUserDefaults] setObject:_dataDict forKey: KET_CARDICT];     
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark- btn action
-(IBAction)cancelDateViewAction:(id)sender
{
    [UIView beginAnimations:@"scroll" context:nil];
    [UIView setAnimationDelay:0.3f];
    CGRect rect = _dateView.frame;
    rect.origin = CGPointMake(0,self.view.frame.size.height);
    _dateView.frame = rect;
    _tableView.frame = CGRectMake(0, 0, _tableView.frame.size.width, _tableView.frame.size.height);
    [UIView commitAnimations];
}
-(IBAction)okDateViewAction:(id)sender
{
    NSDate * selectedDate = [_datePicker date];//获取选取时间  
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy年MM月dd日"];
    NSString *date = [formatter stringFromDate:selectedDate];
    [_dataDict setValue:date forKey:@"购买日期:"];
    [formatter release];
    [self cancelDateViewAction:sender];
    [_tableView reloadData];
}
-(void)switchAction:(id)sender 
{
    UISwitch *btn = (UISwitch *)sender;
    if (btn.on) {
        _carNumber.secureTextEntry = YES;
        _carUserName.secureTextEntry = YES;
    }else {
        _carNumber.secureTextEntry = NO;
        _carUserName.secureTextEntry = NO;
    }
}
#pragma mark- UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


- (NSInteger)tableView:(UITableView *)activeTableView numberOfRowsInSection:(NSInteger)section 
{
    return [[_dataDict allKeys] count]+2;
}

- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *tag = @"carInfoCell";
    UITableViewCell *cell=[aTableView dequeueReusableCellWithIdentifier:[NSString stringWithFormat:@"%@%d",tag,indexPath.row]];
    if (cell==nil) 
    {
        cell =[[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[NSString stringWithFormat:@"%@%d",tag,indexPath.row]] autorelease]; 
        if (indexPath.row < [_titleArray count] || indexPath.row == [_titleArray count]+1) {
            //title
            UILabel* titleLabel = [[UILabel alloc] init];
            titleLabel.backgroundColor = [UIColor clearColor];
            titleLabel.font = [UIFont systemFontOfSize:14];
            titleLabel.frame = CGRectMake(5, 7, 80, 20);
            titleLabel.tag = kTitleLabelTag;
            titleLabel.textAlignment = UITextAlignmentRight;
            [cell addSubview:titleLabel];
            [titleLabel release];
            
            if (indexPath.row <  [_titleArray count] ) {
                switch (indexPath.row) {
                    case 1:
                        if (!_switchView) {
                            _switchView = [[UISwitch alloc] initWithFrame:CGRectMake(220.0f, 6.0f, 100.0f, 28.0f)];
                            [_switchView setOn:NO];
                            [_switchView addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];
                            [cell addSubview:_switchView];
                        }
                        break;
                    case 2:
                    {
                        if (!_carNumber) {
                            _carNumber = [[UITextField alloc] initWithFrame:CGRectMake(100, 10, 150, 31)];
                            _carNumber.clearButtonMode = UITextFieldViewModeWhileEditing;
                            _carNumber.font =[UIFont systemFontOfSize:14.0f];
                            _carNumber.keyboardAppearance = UIKeyboardAppearanceDefault;
                            _carNumber.autocapitalizationType = UITextAutocapitalizationTypeNone;
                            _carNumber.autocorrectionType = UITextAutocorrectionTypeNo;
                            _carNumber.returnKeyType = UIReturnKeyDone;
                            _carNumber.delegate = self;
                            _carNumber.placeholder = @"请输入车牌号码";
                            _carNumber.backgroundColor = [UIColor clearColor];
                            [cell addSubview:_carNumber];
                        }
                    }
                        break; 
                    case 3:
                    {
                        if (!_carUserName) {
                            _carUserName = [[UITextField alloc] initWithFrame:CGRectMake(100, 10, 150, 31)];
                            _carUserName.clearButtonMode = UITextFieldViewModeWhileEditing;
                            _carUserName.font =[UIFont systemFontOfSize:14.0f];
                            _carUserName.keyboardAppearance = UIKeyboardAppearanceDefault;
                            _carUserName.autocapitalizationType = UITextAutocapitalizationTypeNone;
                            _carUserName.autocorrectionType = UITextAutocorrectionTypeNo;
                            _carUserName.returnKeyType = UIReturnKeyDone;
                            _carUserName.delegate = self;
                            _carUserName.placeholder = @"请输入车主姓名";
                            _carUserName.backgroundColor = [UIColor clearColor];
                            [cell addSubview:_carUserName];
                        }
                    }
                        break;
                    default:
                    {
                        UILabel* titleLabel = [[UILabel alloc] init];
                        titleLabel.backgroundColor = [UIColor clearColor];
                        titleLabel.font = [UIFont systemFontOfSize:14];
                        if (indexPath.row == 0) {
                            titleLabel.textColor = [UIColor blueColor]; 
                        }
                        titleLabel.frame = CGRectMake(100, 5, 200, 21);
                        titleLabel.tag = kTitleLabelTag+1;
                        [cell addSubview:titleLabel];
                        [titleLabel release];
                    }
                        break;
                }
            }
        }
        if (indexPath.row == [_titleArray count]) {
            if (!_imageView) {
                _imageView = [[UIImageView alloc] initWithFrame:CGRectMake(25, 0, 120, 80)];
                [cell addSubview:_imageView];
            }
        }
        if (indexPath.row == 6 || indexPath.row == 7 || indexPath.row == 9 ||indexPath.row == 11 ||indexPath.row == 12 || indexPath.row == 13 ||  indexPath.row == 15) {
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.selectionStyle = UITableViewCellSelectionStyleGray;
        }else {
            cell.accessoryType = UITableViewCellAccessoryNone;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
    }
    if (indexPath.row < [_titleArray count]) {
        UILabel* titleLabel = (UILabel*)[cell viewWithTag:kTitleLabelTag];
        if (titleLabel) {
            if (indexPath.row == 1) {
                titleLabel.textColor = [UIColor redColor];
            }
            titleLabel.text = [_titleArray objectAtIndex:indexPath.row];
        }
        
        switch (indexPath.row) {
            case 0:
            {
                UILabel* titleLabel = (UILabel*)[cell viewWithTag:kTitleLabelTag+1];
                if (titleLabel && [_carVin.vinCode length]>0) {
                    titleLabel.text = _carVin.vinCode;
                    titleLabel.textAlignment = UITextAlignmentCenter;
                    titleLabel.textColor = [UIColor blueColor];
                }
            }
                break;
            case 1:
            {
                _switchView.on = (_carVin.isTestSteer==1)?YES:NO;
                if (_switchView.on) {
                    _carNumber.secureTextEntry = YES;
                    _carUserName.secureTextEntry = YES;
                }else {
                    _carNumber.secureTextEntry = NO;
                    _carUserName.secureTextEntry = NO;
                }
            }
                break;
            case 2:
            {
                _carNumber.text = [_carVin.carNumber length]>0?_carVin.carNumber:@"";
            }
                break;
            case 3:
            {
                _carUserName.text = [_carVin.ownerName length]>0?_carVin.ownerName:@"";
            }
                break;
            case 4:
            {
                
            }
                break;
            case 5:
            {
                UILabel* titleLabel = (UILabel*)[cell viewWithTag:kTitleLabelTag+1];
                if (titleLabel) {
                    titleLabel.text = [_carVin.brand length]>0?_carVin.brand:@"";
                }
            }
                break;
            case 6:
            {
                UILabel* titleLabel = (UILabel*)[cell viewWithTag:kTitleLabelTag+1];
                if (titleLabel) {
                    titleLabel.text = [_carVin.manufacturerAddress length]>0?_carVin.manufacturerAddress:@"";
                }
            }
                break;
            case 7:
            {
                UILabel* titleLabel = (UILabel*)[cell viewWithTag:kTitleLabelTag+1];
                if (titleLabel) {
                    titleLabel.text = [_carVin.carType length]>0?_carVin.carType:@"";
                }
            }
                break;
            case 8:
            {
                UILabel* titleLabel = (UILabel*)[cell viewWithTag:kTitleLabelTag+1];
                if (titleLabel) {
                    titleLabel.text = [_carVin.productiveYear length]>0?_carVin.productiveYear:@"";
                }
            }
                break;
            case 9:
            {
                UILabel* titleLabel = (UILabel*)[cell viewWithTag:kTitleLabelTag+1];
                if (titleLabel) {
                    titleLabel.text = [_carVin.country length]>0?_carVin.country:@"";
                }
            }
                break;
            case 10:
            {
                UILabel* titleLabel = (UILabel*)[cell viewWithTag:kTitleLabelTag+1];
                if (titleLabel) {
                    titleLabel.text = [_carVin.literAvg length]>0?_carVin.literAvg:@"";
                }
            }
                break;
            case 11:
            {
                UILabel* titleLabel = (UILabel*)[cell viewWithTag:kTitleLabelTag+1];
                if (titleLabel) {
                    titleLabel.text = [_carVin.maintenanceInterval length]>0?_carVin.maintenanceInterval:@"";
                }
            }
                break;
            case 12:
            {
                UILabel* titleLabel = (UILabel*)[cell viewWithTag:kTitleLabelTag+1];
                if (titleLabel) {
                    titleLabel.text = [_carVin.fuelOilType length]>0?_carVin.fuelOilType:@"";
                }
            }
                break;
            case 13:
            {
                UILabel* titleLabel = (UILabel*)[cell viewWithTag:kTitleLabelTag+1];
                if (titleLabel) {
                    titleLabel.text = [_carVin.carColor length]>0?_carVin.carColor:@"";
                }
            }
                break;
            default:
            {
                UILabel* titleLabel = (UILabel*)[cell viewWithTag:kTitleLabelTag+1];
                if (titleLabel) {
                    titleLabel.text = [_dataDict valueForKey:[_titleArray objectAtIndex:indexPath.row]];
                }
            }break;
        }
    }
    
    if (indexPath.row == [_titleArray count]+1) {
        UILabel* titleLabel = (UILabel*)[cell viewWithTag:kTitleLabelTag];
        if (titleLabel) {
            if (indexPath.row == 1) {
                titleLabel.textColor = [UIColor redColor];
            }
            titleLabel.text = @"更多参数";
        }
    }
    return cell;
}

#pragma mark- UITableViewDelegate
- (CGFloat)tableView:(UITableView *)aTableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    if (indexPath.row == [_titleArray count]) {
        return 80.0f;
    }
    return 40.0f;
}

- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{	
    switch (indexPath.row) {
        case 4:
            //日期选择器
        {
            if (_dateView) {
                CGRect rect = _dateView.frame;
                rect.origin = CGPointMake(0,self.view.frame.size.height);
                _dateView.frame = rect;
                _dateView.hidden = NO;
            }
            [UIView beginAnimations:@"scroll" context:nil];
            [UIView setAnimationDelay:0.3f];
            CGRect rect = _dateView.frame;
            rect.origin = CGPointMake(0,110);
            _dateView.frame = rect;
            _tableView.frame = CGRectMake(0, -90, _tableView.frame.size.width, _tableView.frame.size.height);
            [UIView commitAnimations];
        }
            break;
        default:
            break;
    }
}

#pragma mark- UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField == _carNumber) {
        NSString *text = _carNumber.text;
        if ([text length] > 0) {
            [_dataDict setValue:text forKey:@"车牌号码:"];
        }
        [_carNumber becomeFirstResponder];
    } else if (textField == _carUserName) {
        NSString *text = _carUserName.text;
        if ([text length] > 0) {
            [_dataDict setValue:text forKey:@"车主姓名:"];
        }
        [_carUserName resignFirstResponder];
    }
    return YES;
}

#pragma mark - touch event
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:_tableView];
    if (!CGRectContainsPoint(_carNumber.frame, point) && !CGRectContainsPoint(_carUserName.frame, point)) {
        if ([_carNumber isFirstResponder])
            [_carNumber resignFirstResponder];
        if ([_carUserName isFirstResponder])
            [_carUserName resignFirstResponder];
    }
}

@end
